import { createConnection } from 'typeorm';
import { config } from 'dotenv';
import axios from 'axios';
import {  Api as TLSSigAPIv2 } from  'tls-sig-api-v2'

// 加载环境变量
config();

// 腾讯云IM配置
const SDKAppID = Number(process.env.TENCENT_SDKAPPID);
const adminUserId = process.env.TENCENT_ADMIN_USERID || 'administrator'; // 修改默认值为administrator
const secretKey = process.env.TENCENT_SECRETKEY;

// 检查配置
if (!SDKAppID || !secretKey) {
  console.error('错误: 腾讯云IM配置缺失，请检查环境变量');
  process.exit(1);
}

console.log('腾讯云IM配置:');
console.log(`SDKAppID: ${SDKAppID}`);
console.log(`管理员用户ID: ${adminUserId}`);
console.log(`密钥长度: ${secretKey ? secretKey.length : 0}字符`);

// 生成腾讯云IM的用户ID
function getTencentUserId(userId: number): string {
  return `user_${userId}`;
}

// 导入单个用户到腾讯云IM
async function importUserToTencentIM(user: any, api: TLSSigAPIv2): Promise<boolean> {
  try {
    const tencentUserId = getTencentUserId(user.id);
    
    // 生成管理员签名
    const adminSig = api.genUserSig(adminUserId, 86400);
    
    // 导入用户到腾讯云IM
    const url = `https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=${SDKAppID}&identifier=${adminUserId}&usersig=${adminSig}&random=${Math.floor(Math.random() * 1000000)}&contenttype=json`;
    
    const requestBody = {
      UserID: tencentUserId,
      Nick: user.nickname || `用户${user.id}`,
      FaceUrl: user.avatar || ''
    };
    
    console.log(`正在导入用户: ID=${user.id}, 昵称=${requestBody.Nick}`);
    console.log(`请求URL: ${url}`);
    console.log(`请求体: ${JSON.stringify(requestBody)}`);
    
    const response = await axios.post(url, requestBody);
    
    console.log(`响应: ${JSON.stringify(response.data)}`);
    
    if (response.data.ErrorCode !== 0) {
      throw new Error(`导入用户失败: ${response.data.ErrorInfo}`);
    }
    
    console.log(`成功导入用户: ID=${user.id}, 腾讯云ID=${tencentUserId}`);
    
    // 保存映射关系到数据库
    try {
      await saveUserMapping(user.id, tencentUserId);
    } catch (mappingError) {
      console.warn(`保存用户映射关系失败: ${mappingError.message}`);
    }
    
    return true;
  } catch (error) {
    console.error(`导入用户 ${user.id} 失败: ${error.message}`);
    if (error.response) {
      console.error('响应数据:', JSON.stringify(error.response.data));
      console.error('响应状态:', error.response.status);
      console.error('响应头:', JSON.stringify(error.response.headers));
    }
    return false;
  }
}

// 保存用户映射关系
async function saveUserMapping(userId: number, tencentUserId: string): Promise<void> {
  try {
    const connection = await getConnection();
    
    // 检查表是否存在
    const tableExists = await connection.query(`
      SELECT COUNT(*) as count 
      FROM information_schema.tables 
      WHERE table_schema = DATABASE() 
      AND table_name = 'user_message_mapping'
    `);
    
    if (parseInt(tableExists[0].count) === 0) {
      console.log('用户消息映射表不存在，创建表...');
      await connection.query(`
        CREATE TABLE IF NOT EXISTS user_message_mapping (
          id INT AUTO_INCREMENT PRIMARY KEY,
          userId INT NOT NULL,
          tencentUserId VARCHAR(255) NOT NULL,
          createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          UNIQUE KEY idx_user_id (userId),
          UNIQUE KEY idx_tencent_user_id (tencentUserId)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
      `);
    }
    
    // 检查映射是否已存在
    const existingMapping = await connection.query(`
      SELECT id FROM user_message_mapping WHERE userId = ?
    `, [userId]);
    
    if (existingMapping.length > 0) {
      // 更新现有映射
      await connection.query(`
        UPDATE user_message_mapping 
        SET tencentUserId = ?, updatedAt = NOW() 
        WHERE userId = ?
      `, [tencentUserId, userId]);
    } else {
      // 创建新映射
      await connection.query(`
        INSERT INTO user_message_mapping (userId, tencentUserId) 
        VALUES (?, ?)
      `, [userId, tencentUserId]);
    }
  } catch (error) {
    console.error(`保存用户映射关系失败: ${error.message}`);
    throw error;
  }
}

// 获取数据库连接
let dbConnection: any = null;
async function getConnection() {
  if (dbConnection) {
    return dbConnection;
  }
  
  dbConnection = await createConnection({
    name: 'importConnection',
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: Number(process.env.DB_PORT) || 3306,
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '123456',
    database: process.env.DB_DATABASE || 'hdq-news',
    synchronize: false
  });
  
  return dbConnection;
}

// 检查管理员账号是否已导入
async function checkAndImportAdminUser(api: TLSSigAPIv2): Promise<boolean> {
  try {
    console.log('检查管理员账号是否已导入...');
    
    // 生成管理员签名
    const adminSig = api.genUserSig(adminUserId, 86400);
    
    // 检查管理员账号是否存在
    const checkUrl = `https://console.tim.qq.com/v4/im_open_login_svc/account_check?sdkappid=${SDKAppID}&identifier=${adminUserId}&usersig=${adminSig}&random=${Math.floor(Math.random() * 1000000)}&contenttype=json`;
    
    const checkResponse = await axios.post(checkUrl, {
      CheckItem: [
        { UserID: adminUserId }
      ]
    });
    
    if (checkResponse.data.ErrorCode !== 0) {
      throw new Error(`检查管理员账号失败: ${checkResponse.data.ErrorInfo}`);
    }
    
    const adminExists = checkResponse.data.ResultItem[0].AccountStatus === 'Imported';
    
    if (!adminExists) {
      console.log('管理员账号不存在，正在导入...');
      
      // 导入管理员账号
      const importUrl = `https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=${SDKAppID}&identifier=${adminUserId}&usersig=${adminSig}&random=${Math.floor(Math.random() * 1000000)}&contenttype=json`;
      
      const importResponse = await axios.post(importUrl, {
        UserID: adminUserId,
        Nick: '管理员',
        FaceUrl: ''
      });
      
      if (importResponse.data.ErrorCode !== 0) {
        throw new Error(`导入管理员账号失败: ${importResponse.data.ErrorInfo}`);
      }
      
      console.log('管理员账号导入成功');
    } else {
      console.log('管理员账号已存在');
    }
    
    return true;
  } catch (error) {
    console.error(`检查或导入管理员账号失败: ${error.message}`);
    if (error.response) {
      console.error('响应数据:', JSON.stringify(error.response.data));
    }
    return false;
  }
}

// 主函数
async function importAllUsersToTencentIM() {
  console.log('开始导入所有用户到腾讯云IM...');
  
  try {
    // 创建TLSSigAPIv2实例
    const api = new TLSSigAPIv2(SDKAppID, secretKey);
    
    // 检查并导入管理员账号
    const adminReady = await checkAndImportAdminUser(api);
    if (!adminReady) {
      console.error('管理员账号准备失败，无法继续导入用户');
      return;
    }
    
    // 获取数据库连接
    const connection = await getConnection();
    
    // 获取所有用户
    const users = await connection.query(`
      SELECT id, username, nickname, avatar 
      FROM users 
      WHERE status = 1
    `);
    
    console.log(`找到 ${users.length} 个用户需要导入`);
    
    // 导入用户计数
    let successCount = 0;
    let failCount = 0;
    
    // 批量导入用户
    for (const user of users) {
      try {
        const success = await importUserToTencentIM(user, api);
        if (success) {
          successCount++;
        } else {
          failCount++;
        }
        
        // 添加延迟，避免请求过快
        await new Promise(resolve => setTimeout(resolve, 200));
      } catch (error) {
        console.error(`处理用户 ${user.id} 时出错: ${error.message}`);
        failCount++;
      }
    }
    
    console.log(`导入完成! 成功: ${successCount}, 失败: ${failCount}, 总计: ${users.length}`);
  } catch (error) {
    console.error(`导入用户时出错: ${error.message}`);
  } finally {
    // 关闭数据库连接
    if (dbConnection) {
      await dbConnection.close();
      console.log('数据库连接已关闭');
    }
  }
}

// 执行导入
importAllUsersToTencentIM()
  .then(() => {
    console.log('脚本执行完成');
    process.exit(0);
  })
  .catch(error => {
    console.error('脚本执行失败:', error);
    process.exit(1);
  });
